package cn.izeno.wx.models

import org.dom4j.Document

/**
 * 微信公众号消息
 */
abstract class Message(
    var msgId: Long? = null,
    var msgType: String? = null,
    var createTime: Long = System.currentTimeMillis(),

    var toUserName: String = "",
    var fromUserName: String = ""
)  {


  /**
   * 解析xml填充消息
   */
  open fun parseXML(document: Document) {
    this.msgId = document.selectSingleNode("xml/MsgId").text?.toLong()
    this.toUserName = document.selectSingleNode("/xml/ToUserName")?.text ?: ""
    this.fromUserName = document.selectSingleNode("/xml/FromUserName")?.text ?: ""
    this.createTime = document.selectSingleNode("/xml/CreateTime")?.text?.toLong() ?: System.currentTimeMillis()
  }

  abstract fun toXMLString(): String

  companion object {
    val MSG_TYPE_TEXT = "text"
    val MSG_TYPE_EVENT = "event"
    val MSG_TYPE_IMG = "image"
    val MSG_TYPE_VOICE = "voice"
    val MSG_TYPE_VIDEO = "video"
    val MSG_TYPE_LOCATION = "location"
    val MSG_TYPE_LINK = "link"

    val MSG_TYPE_NEWS = "news"
    //</editor-fold>

    fun createMessage(msgType: String?): Message = when {
      MSG_TYPE_TEXT == msgType -> TextMessage()
      MSG_TYPE_EVENT == msgType -> EventMessage()
      MSG_TYPE_VOICE == msgType -> VoiceMessage()
      else -> error("error msgType: $msgType")
    }
  }

}
